#include "udpServer.hpp"
#include "onlineUser.hpp"
#include <memory>
#include <fstream>
#include <unordered_map>
#include <signal.h>
using namespace Server;

static void Usage()
{
    cout << "Usage: 可执行程序 local_port" << endl;
}

const string dictAdd = "./dict.txt";
unordered_map<string, string> dict;

onlineUser olUser;

void routeMessage(int sockfd, string clientIp, uint16_t clientPort, string message)
{
    // 如果收到的消息是oline，就添加用户
    if (message == "online")
        olUser.addUser(clientIp, clientPort);
    // 删除用户
    if (message == "offline")
        olUser.delUser(clientIp, clientPort);

    if (olUser.isOL(clientIp, clientPort))
    {
        // 用户在线，所发的消息广播给所有在线用户
        olUser.broadcastMessage(sockfd, clientIp, clientPort, message);
    }
    else // 不在线，单独给这个用户提醒其输入online
    {
        struct sockaddr_in client;
        bzero(&client, sizeof(client));
        client.sin_family = AF_INET;
        client.sin_port = htons(clientPort);
        client.sin_addr.s_addr = inet_addr(clientIp.c_str());

        string responce = "你还没上线，上线请输入: online";
        sendto(sockfd, responce.c_str(), responce.size(), 0, (struct sockaddr *)&client, sizeof(client));
    }
}

//  ./udpServer port
int main(int argc, char *argv[])
{

    if (argc != 2)
    {
        Usage();
        exit(USAGE_ERR);
    }

    uint16_t port = atoi(argv[1]); // 将字符串转化为int，uint16_t，只存2个低字节

    unique_ptr<udpServer> usvr(new udpServer(routeMessage, port));

    usvr->initServer();
    usvr->start();
    return 0;
}
